import os

import requests
from bs4 import BeautifulSoup
import time

# 设置请求头模拟浏览器
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

url = 'https://movie.douban.com/'

def fetch_now_playing():
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
    except requests.RequestException as e:
        print("请求失败：", e)
        return []

    soup = BeautifulSoup(response.text, 'html.parser')

    # 定位“正在热映”区域（根据网页结构，可能需要更新）
    now_playing_section = soup.find('div', {'class': 'screening-bd'})
    if not now_playing_section:
        print("未找到正在热映区域，可能页面结构已变动")
        return []

    movies = []

    # 遍历每部电影卡片
    for item in now_playing_section.find_all('li', class_='ui-slide-item', limit=50):
        title_tag = item.get('data-title')
        score_tag = item.get('data-rate')
        if title_tag:
            movies.append({
                'title': title_tag.strip(),
                'score': score_tag.strip() if score_tag and score_tag.strip() else '暂无评分'
            })

    return movies

if __name__ == '__main__':
    print("正在获取豆瓣正在热映电影...")
    time.sleep(1)  # 简单延迟，避免被封
    movies = fetch_now_playing()

    # 写入文件
    file_path = os.path.join(os.path.dirname(__file__), 'douban_now_playing.txt')
    with open(file_path, 'w', encoding='utf-8') as f:
        for idx, m in enumerate(movies, 1):
            line = f"{idx}. {m['title']} - 评分：{m['score']}\n"
            f.write(line)
    print(f"已保存 {len(movies)} 部电影信息到 {file_path}")